// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package api

import (
	"fmt"
	//"math/rand"
	"sync"
	//"time"

	//"github.com/coreos/etcd/raft/raftpb"
)

// a network interface
type NetWorkInterface interface {
	send(m multiMessage)
	recv() <-chan []multiMessage
}


type multiraftNetwork struct {
	mu           sync.Mutex
	recvQueues   [] multiMessage
	readyc  		chan []multiMessage
}


func newMultiRaftNetwork() NetWorkInterface {
	pn := &multiraftNetwork{
		recvQueues:   make([]multiMessage, 0),
		readyc: make(chan []multiMessage),
	}	
	return pn
}


func (rn *multiraftNetwork) send(m multiMessage) {
	rn.mu.Lock()
		
	rn.recvQueues = append(rn.recvQueues, m)
	if len(rn.recvQueues) > 1 {		
		select {
			case rn.readyc<-rn.recvQueues:
				rn.recvQueues = []multiMessage{}	
			default:
				// drop messages when the receiver queue is full.
				fmt.Printf("drop message when the receiver queue is full\n")
		}		
	}
	
	rn.mu.Unlock()
	fmt.Printf("发送数据结束\n")
}

func (rn *multiraftNetwork) recv() <-chan []multiMessage {
	return rn.readyc
}

